<?PHP
// PHP World of Warcraft item sending script
// Created by Gachl (Daniel Vogel)

include_once "configa.php";



$config = "scripts.inc.php";
$usingtype = "n";
$configfilename = "config_items.cfg";
// Edit the following function that it returns the amount in copper (1 gold = 10'000 copper)
// Default value: halt the sellprice but minimum one gold.
// Parameter: $buyprice: The amount of copper you have to pay if you want to buy the item ingame.
//            $sellprice: The amount of copper you have to pay if you want to sell the item ingame.
function fCalculateItemPrice($buyprice, $sellprice) {
  $price = $sellprice / 2;
  return ($price < 0) ? 0 : $price;
}

// ########################
// #Don't change from here#
// ########################
require_once($config);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title><?= $websitetitle ?></title>
  <script type="text/javascript">
  <!--
  // This code is not very proper... (i'm not that good in js...)
	function addItem() {
  	var itm = this.document.getElementById('items');
  	var count = this.document.getElementById('count').value;
  	count++;
  	this.document.getElementById('count').value = count;
  
  	var newItms = document.createElement("span");
  	itm.appendChild(newItms);
  	newItms.innerHTML='Item ' + count + ': <input type="text" name="item' + count + '"><br>';
	}
	-->
  </script>
</head>
<body>
  
  <?PHP
// Script
$wuser = fGetUser($userid);
if ($wuser === false)
  die("The user with the user id " . $userid . " does not exists!" . ($userid == 0 ? " Website admin please set up the current user id settings!" : ''));

// Load config file
// This code is stupid <.<
if ($usingtype != "n") {
	$conffile = "";
	do {
		if (!file_exists($configfilename)) {
			if (!is_writable(dirname($configfilename))) {
				die("Please create a file with the name &quot;$configfilename&quot; and make it writable (chmod 777).");
			}
			$fh = fopen($configfilename, 'w');
			fwrite($fh, $usingtype . "\n");
			fclose($fh);
		}
		$fh = fopen($configfilename, "r");
		while (!feof($fh))
			$conffile = fread($fh, 1024);
		fclose($fh);
		if (trim($conffile) != "") {
			$conffile = split("\n", $conffile);
			$config['usingtype'] = $conffile[0];
		} else {
			$config['usingtype'] = "n";
		}
		if ($config['usingtype'] != $usingtype) {
			$fh = fopen($configfilename, "w");
			fwrite($fh, $usingtype);
			fclose($fh);
		}
	} while ($config['usingtype'] != $usingtype);
	unset($conffile[0]);
	foreach ($conffile as $confline) {
		$confline = split(";", $confline);
		$config[$confline[0]] = $confline[1];
	}

	if ($usingtype == "e") {
		$now = time();
		$sub = (intval($now) - (intval($config[1]) + ($usingspan * 60)));
		if (!empty($config[1]) && ($sub < 0))
			die("This tool cannot be used at the moment. You have to wait " . round($sub * (-1) / 60, 1) . " minute(s).");
	}
	if ($usingtype == "a") {
		$now = time();
		$sub = (intval($now) - (intval($config[$userid]) + ($usingspan * 60)));
		if (!empty($config[$userid]) && ($sub < 0))
			die("You can't use this tool. You have to wait " . round($sub * (-1) / 60, 1) . " minute(s).");
	}
}

// POST data sent?
if (!empty($_POST['sent'])) {
	$items = Array(); // Create a new array for the items
	$itemcount = intval($_POST['count']); // How many items
	for ($i = 0; $i < $itemcount; $i++)
		$items[] = intval($_POST['item' . ($i + 1)]); // Add item to array
	// Create a list with _valid_ items
	$sitems = Array(); // Valid items
	foreach ($items as $item) {
		if (!empty($item) && ($item < $maxitemid) && ($item > 1)) {
			$exist = mysql_fetch_assoc(fMySQL_query('SELECT COUNT(`entry`) AS `count` FROM `items` WHERE `entry` = ' . $item . ';', DB_WORLD));
			if (intval($exist['count']) === 1) { // If the item exists in the database get all required informations
				$itm = mysql_fetch_assoc(fMySQL_query('SELECT `entry`, `sellprice`, `buyprice`, `name1` FROM `items` WHERE `entry` = ' . $item . ';', DB_WORLD));
				$price = fCalculateItemPrice(intval($itm['buyprice']), intval($itm['sellprice']));
				$itmbx['id'] = $item; // The valid item...
				$itmbx['price'] = $price;
				$itmbx['name'] = $itm['name1'];
				$sitems[] = $itmbx; // add it
			}
		}
	}
	$charid = intval($_POST['cid']); // Get the character id
	if ($usingtype == "c") {
		$now = time();
		$sub = (intval($now) - (intval($config[$charid]) + ($usingspan * 60)));
		if (!empty($config[$charid]) && ($sub < 0))
			die("You can't use this tool with this character. You have to wait " . round($sub * (-1) / 60, 1) . " minute(s).");
	}
  if (empty($_POST['accept'])) {
		echo '<form action="?" method="POST">
    <input type="hidden" name="cid" value="' . $charid . '">Following items will be sent to your character:<br>
    <table><tr><td><b>Id</b></td><td><b>Name</b></td><td><b>Preis</b></td></tr>' . "\n";
		$overall = 0; // The amount of copper of all items
		$lc = 1; // counter for the form
		foreach ($sitems as $itm) {
			$ch = intval(substr($itm['price'], -2)); // copper (2d)
			$si = intval(substr(round(intval($itm['price']) / 100), -2)); // silver (2d)
			$go = intval(round(intval($itm['price']) / 10000)); // gold
			echo "<tr><td>" . $itm['id'] . "</td><td>" . '<input type="hidden" name="item' . $lc . '" value="' . $itm['id'] . '">' . $itm['name'] . "</td><td>$go G $si S $ch C</td></tr>\n";
			$overall += $itm['price'];
			$lc++;
		}
		$ch = intval(substr($overall, -2)); // overall copper
		$si = intval(substr(round(intval($overall) / 100), -2)); // overall silver
		$go = intval(round(intval($overall) / 10000)); // overall gold
		echo "<tr><td><b>Total</b></td><td><b>" . count($sitems) . " Items</b></td><td><b>$go G $si S $ch C</td></tr>\n";
		echo "</table>" . '<input type="hidden" name="count" value="' . $itemcount . '"><input type="hidden" name="sent" value="yes"><input type="submit" name="accept" value="Sent items"></form>';
	} else {
		if (!($char = mysql_fetch_assoc(fMySQL_query("SELECT * FROM `characters` WHERE `guid` = $charid;", DB_ACCOUNT))))
		  die("The character id $charid does not exists.");
		if (intval($char['acct']) != intval($wuser['acct']))
			die('This is not your character!');
		if (intval($char['online']) != 0)
			die('You are currently logged in with that character. You have to log out to send items!');
		
		// Calculate the overall price
		$overall = 0;
		foreach ($sitems as $itm)
			$overall += $itm['price'];
		
		$char = mysql_fetch_assoc(fMySQL_query("SELECT `name`, `gold` FROM `characters` WHERE `guid` = $charid;", DB_ACCOUNT)); // Get character informations
		$charname = $char['name']; 
		if ($char['gold'] < $overall) // Check if he has enough gold
			die('You have not enough gold!');
		
		$chargold = $char['gold'] - $overall; // Set new gold
		fMySQL_query("UPDATE `characters` SET `gold` = $chargold WHERE `guid` = $charid;", DB_ACCOUNT);
		
		// Send items to the player
		foreach ($sitems as $item) {
			$result = mysql_fetch_assoc(fMySQL_query("SELECT MAX(`guid`) AS `maxguid` FROM `playeritems`;", DB_ACCOUNT));
			$itemGUID = $result['maxguid'] + 1;
			
			$result = mysql_fetch_assoc(fMySQL_query("SELECT MAX(`slot`) AS `maxslot` FROM `playeritems` WHERE `ownerguid` = '$senderid';", DB_ACCOUNT));
			$itemSlot = $result['maxslot'] + 1;
			
			$result = mysql_fetch_assoc(fMySQL_query("SELECT MAX(`message_id`) AS `mid` FROM `mailbox`;", DB_ACCOUNT));
			$messageID = $result['mid'] + 1;
			
			// These queries are from a forum.. i dont know it anymore, but credits go to them ;) 
			$add = "INSERT INTO playeritems SET " .
					"ownerguid=$senderid, " .
					"guid='$itemGUID', " .
					"entry='".$item['id']."', " .
					"count=1, " .
					"slot='$itemSlot', " .
					"enchantments=''";
			$endTime = round(microtime(true));
			
			$search = Array("%char%", "%item%");
      $replace = Array($charname, $item['name']);
			$messagetext = str_replace($search, $replace, $messagetext);
			
			$sql = "INSERT INTO mailbox SET " .
					"message_id='$messageID', " .
					"player_guid='$charid', " .
					"sender_guid=$senderid, " .
					"subject='" . addslashes($item['name']) . "', " .
					"body='$messagetext', " .
					"attached_item_guids='$itemGUID,', " .
					"stationary=41, " .
					"delivery_time='$endTime'";
			fMySQL_query($add, DB_ACCOUNT);
			fMySQL_query($sql, DB_ACCOUNT);
		}
		// Save config file
		if ($usingtype != "n") {
			$fh = fopen($configfilename, "w");
			fwrite($fh, $usingtype . "\n");
			switch ($usingtype) {
			case "a":
				$config[$userid] = time();
				break;
			case "c":
				$config[$charid] = time();
				break;
			case "e":
				$config[1] = time();
				break;
			}
			foreach ($config as $id => $time) {
				if (($id != "usingtype") && !empty($id)) {
					fwrite($fh, $id . ";" . $time . "\n");
				}
			}
			fclose($fh);
		}
		// Congrats!
		echo "The items have been sent successfully. You can now log in and check your ingame mailbox.";
	}
}

if (empty($_POST['sent'])) {
?>
  <form action="?" method="POST">
    Charakter: <select name="cid">
<?PHP
$res = fMySQL_query("SELECT `guid`, `name` FROM `characters` WHERE `acct` = " . $wuser['acct'] . ";", DB_ACCOUNT);
while ($row = mysql_fetch_assoc($res))
	echo '<option value="'.$row['guid'].'">'.$row['name'].'</option>'."\n";
?>
    </select>
  	<div id="items">
  	 Item 1: <input type="text" name="item1"><br>
  	</div>
  	<a href="javascript:addItem()">Add one</a><br>
  	<input type="hidden" name="count" id="count" value="1">
    <input type="submit" name="sent" value="Get items">
	</form>
<?PHP
}
?>
</body>
</html>
<!-- This script is written by Gachl (Daniel Vogel). http://codefreak.net http://data-universal.net http://blog.codefreak.net Queries: <?= $qcount ?> -->